package com.burybell.storage.system;

import com.burybell.storage.domain.Storage;
import com.burybell.storage.system.bean.BurstInputStream;
import com.burybell.storage.system.bean.GetBean;
import com.burybell.storage.utils.IOUtils;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class StorageTemplate {


    private String base = null;
    private Integer buffer = 1024;
    private Integer sliceMin = 1024 * 1024 * 100;
    private String name = null;

    public StorageTemplate(String name,String base,Integer buffer,Integer sliceMin) {
        this.name = name;
        this.base = base;
        this.buffer = buffer;
        this.sliceMin = sliceMin;
    }

    /**
     * 获取所有场景
     * @return
     */
    public List<String> scenes() {
        File file = new File(base);
        List<String> scenes = new ArrayList<>();
        for (File scene : Objects.requireNonNull(file.listFiles())) {
            scenes.add(scene.getName());
        }
        return scenes;
    }

    public String getName() {
        return name;
    }

    /**
     * 获取系统使用大小
     * @return
     */
    public Long totalSize() {
        File file = new File(base);
        return IOUtils.getDirSize(file);
    }

    public Storage set(String scene, String definition, Long size, InputStream inputStream) {
        if (size < sliceMin){
            return StorageSystem.upload(base,scene,definition,size,inputStream,1,buffer);
        } else {
            int slice = Math.toIntExact(size / sliceMin);
            return StorageSystem.upload(base,scene,definition,size,inputStream,slice,buffer);
        }
    }

    /**
     * 获取文件
     * @param scene
     * @param year
     * @param month
     * @param day
     * @param sid
     * @return
     */
    public BurstInputStream get(String scene, Integer year, Integer month, Integer day, String sid) {
        return StorageSystem.getInputStream(base,scene,year,month,day,sid);
    }

    /**
     * 获取文件
     * @param getBean
     * @return
     */
    public BurstInputStream get(GetBean getBean){
        return get(getBean.getScene(),getBean.getYear(),getBean.getMonth(),getBean.getDay(),getBean.getSid());
    }
}
